package com.jeesite.modules.ic.channel.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.config.CardStatus;
import com.jeesite.modules.ic.channel.CardDataService;
import com.jeesite.modules.ic.channel.config.TokenApiConfig;
import com.jeesite.modules.ic.entity.IcCard;
import com.jeesite.modules.ic.entity.IcPackage;
import com.jeesite.modules.ic.service.IcCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 泽米科技
 */
@Component("card_data_1")
@Slf4j
public class ZemiCardInfoServiceImpl implements CardDataService {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CatchService catchService;

    /**
     * 获取流量卡信息
     * @param iccid
     * @return
     */
    public IcCard getCardInfoByIccid(String iccid) {
        IcCard oneCard = new IcCard();
        if(oneCard==null){
            oneCard = new IcCard();
            oneCard.setIccid(iccid);
        }
        getCardInfoByIccid(oneCard);
        return oneCard;
    }



    /**
     * 获取流量卡信息
     * @param oneCard
     * @return
     */
    public void getCardInfoByIccid(IcCard oneCard) {
        String iccid = oneCard.getIccid();
        String result = getCardInfo(iccid);
        JSONObject jsonObjectTaocan = JSONObject.parseObject(result);
        Boolean success = jsonObjectTaocan.getBoolean("success");
        Integer code = jsonObjectTaocan.getInteger("code");
        if(success && code == 0){
            oneCard.setChannalId("1");
            jsonToCard(jsonObjectTaocan,oneCard);
            if(oneCard.getRealStatus()==null){
                String devStatus = getDevStatus(iccid);
                JSONObject jsonObject = JSONObject.parseObject(devStatus);
                if(jsonObject.getBoolean("success") && jsonObject.getInteger("code") == 0){
                    jsonToCardStatus(jsonObject,oneCard);
                }
            }
        }
    }

    /**
     * 卡状态JSON数据同步到卡对象
     * @param jsonObject
     * @param oneCard
     */
    public void jsonToCardStatus(JSONObject jsonObject,IcCard oneCard){
        JSONObject data = jsonObject.getJSONObject("data");
        Integer status = data.getInteger("status");//设备状态(1:已激活；2:可激活；3:已停用；4:已失效；5:可测试；6:库存；7:已更换；8:已清除;)
        Integer isRealName = data.getInteger("isRealName");//实名状态(0:需要实名未实名;1:需要实名已实名;2:不需实名未实名;3:不需实名已实名;)
            Integer onlineStatus = data.getInteger("onlineStatus");//设备在线状态(0:离线；1:在线;)
        String imei = data.getString("imei");//设备在线状态(0:离线；1:在线;)
        oneCard.setImei(imei);
        oneCard.setDevStatus(onlineStatus!=null?onlineStatus+"":CardStatus.OFFLINE.getNum());
        if(isRealName==0){
            oneCard.setRealStatus(CardStatus.NEEDREAL.getNum());
        }
        if(isRealName==1){
            oneCard.setRealStatus(CardStatus.YIREAL.getNum());
        }
        if(isRealName==2){
            oneCard.setRealStatus(CardStatus.NONEEDREAL.getNum());
        }
        if(isRealName==3){
            oneCard.setRealStatus(CardStatus.YIREAL.getNum());
        }
    }

    /**
     * 卡数据转对象
     * @param jsonObjectTaocan
     * @param oneCard
     */
    public void jsonToCard(JSONObject jsonObjectTaocan,IcCard oneCard){
        //数据
        JSONObject data = jsonObjectTaocan.getJSONObject("data");
        //续费队列参数说明
        JSONArray renewlist = data.getJSONArray("renewlist");
        JSONObject jsonObject = renewlist.getJSONObject(0);
        //套餐参数说明
        JSONArray packageList = jsonObject.getJSONArray("packageList");
        JSONObject listJSONObject = new JSONObject();
        for (int i = 0; i < packageList.size(); i++) {
            JSONObject packageOne = packageList.getJSONObject(i);
            int type = packageOne.getIntValue("type");
            if(type==1){
                listJSONObject = packageOne;
                oneCard.setPackageId(packageOne.getString("packageId"));
            }
        }
        //总流量
        Double flowTotal = data.getDouble("flowTotal");
        oneCard.setTotalFlow(flowTotal.toString());
        //已用流量
        Double flowTotalUsage = data.getDouble("flowTotalUsage");
        oneCard.setUseFlow(flowTotalUsage.toString());
        //剩余流量
        double sub = NumberUtils.sub(flowTotal, flowTotalUsage);
        oneCard.setSurplusFlow(sub+"");
        //开始时间
        Integer startTime = jsonObject.getInteger("startTime");
        oneCard.setBegintime(new Date(startTime*1000L));
        //结束时间
        Integer endTime = jsonObject.getInteger("endTime");
        oneCard.setEndtime(new Date(endTime*1000L));
        //套餐名称
        oneCard.setTaocanName(listJSONObject.getString("packageName"));
        //1:已激活；2:可激活；3:已停用；4:已失效；5:可测试；6:库存；7:已更换；8:已清除;
        Integer status = data.getInteger("status");
        String cardStatus = "1";

        if(status==1){
            cardStatus = CardStatus.ZHENGCHANG.getNum();//正常
        }
        if(status==2){
            cardStatus = CardStatus.WEISHIYONG.getNum();//静默期
        }
        if(status==3){
            cardStatus = CardStatus.TINGYONG.getNum();//已停用
        }
        if(status==4){
            cardStatus = CardStatus.SHIXIAO.getNum();//已失效
        }
        if(status==5){
            cardStatus = CardStatus.WEISHIYONG.getNum();//测试期
        }
        if(status==6){
            cardStatus = CardStatus.WEISHIYONG.getNum();//静默期
        }
        if(status==7){
            cardStatus = CardStatus.SHIXIAO.getNum();//已失效
        }
        if(status==8){
            cardStatus = CardStatus.TINGYONG.getNum();//停用
        }

        oneCard.setCardStatus(cardStatus);
    }

    /**
     * 拉取渠道卡数据
     * @param iccid
     * @return
     */
    public String getCardInfo(String iccid){
        String accessToken = getAccessTokenCache();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Tenant", TokenApiConfig.TENANTID);
        httpHeaders.add("Authorization", "Bearer "+accessToken);

        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> result4 = restTemplate.exchange(TokenApiConfig.APPURL+"/platform/api/usage/current-renewlist-usage-details" + "?realTime=true&iccid="+iccid, HttpMethod.GET, formEntity,String.class);
        String result = result4.getBody();
        log.info("流量卡"+iccid+"查询--->"+result);
        if(isPingZhengGuoqi(result)){
            result = getCardInfo(iccid);
        };
        return result;
    }


    /**
     * 获取设备状态
     * @param iccid
     * @return
     */
    public String getDevStatus(String iccid){
        String accessTokenCache = getAccessTokenCache();
        HttpHeaders headers = new HttpHeaders();
        headers.set("content-type", "application/json");
        headers.set("Tenant", TokenApiConfig.TENANTID);
        headers.set("Authorization", "Bearer "+ accessTokenCache);

        HashMap<String, Object> map = new HashMap<>();
        map.put("iccid", iccid);

        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        String result = restTemplate.postForObject(TokenApiConfig.APPURL+"/platform/api/device/base-info", httpEntity, String.class);
        log.info("设备状态："+result);
        if(isPingZhengGuoqi(result)){
            result = getDevStatus(iccid);
        };
        return result;
    }

    public boolean isPingZhengGuoqi(String result){
        JSONObject jsonObject = JSONObject.parseObject(result);
        Boolean success = jsonObject.getBoolean("success");
        String msg = jsonObject.getString("msg");
        if(!success && "用户凭证已过期".equals(msg)){
            catchService.delete("zemi_access_token");
            return true;
        }
        return false;
    }


    /**
     * 获取流量卡token 存储到缓存中
     */
    public String getAccessTokenCache(){

        String access_token = catchService.get("zemi_access_token");
        if(StringUtils.isEmpty(access_token)){
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            httpHeaders.add("Tenant", TokenApiConfig.TENANTID);
            httpHeaders.add("Authorization", TokenApiConfig.getLoginAuthorization());

            MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            postParameters.add("username",TokenApiConfig.USERNAME);
            postParameters.add("password",TokenApiConfig.getEncodePassWord());
            postParameters.add("grant_type","password");
            postParameters.add("scope","server");

            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, httpHeaders);
            String result = restTemplate.postForObject(TokenApiConfig.APPURL+"/auc/oauth/token", httpEntity, String.class);
            log.info("流量卡接口获取token---------------"+result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            access_token = jsonObject.getString("access_token");
            Integer expires_in = jsonObject.getInteger("expires_in");
            catchService.add("zemi_access_token",access_token,expires_in-300, TimeUnit.SECONDS);
        }
        log.info("流量卡获取token---------------"+access_token);
        return access_token;
    }

    @Override
    public List<IcPackage> getPackage() {
        String s = synPackageList();
        List<IcPackage> list = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(s);
        if(jsonObject.getBoolean("success")&& jsonObject.getIntValue("code")==0){
            JSONObject data1 = jsonObject.getJSONObject("data");
            JSONArray data = data1.getJSONArray("packageList");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject1 = data.getJSONObject(i);
                IcPackage icPackage = jsonToPackage(jsonObject1);
                list.add(icPackage);
            }
        }
        return list;
    }

    /**
     * 获取套餐列表
     */
    public String synPackageList(){
        String accessTokenCache = getAccessTokenCache();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Tenant", TokenApiConfig.TENANTID);
        headers.set("Authorization", "Bearer "+ accessTokenCache);
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(TokenApiConfig.APPURL + "/platform/api/package/list", HttpMethod.GET, entity, String.class);

        String result = response.getBody();
        log.info(result);
        if(isPingZhengGuoqi(result)){
            result = synPackageList();
        };
        return result;

    }

    /**
     * 套餐转对象
     */
    public IcPackage jsonToPackage(JSONObject jsonObject){
        IcPackage icPackage = new IcPackage();
        //套餐名称
        icPackage.setName(jsonObject.getString("packageName"));
        //渠道套餐ID
        icPackage.setChannelPackageId(jsonObject.getString("packageId"));
        //总流量（单位：MB），值为-1时则为超级流量
        icPackage.setZongliulkiang(jsonObject.getDouble("flowTotal").toString());
        //有效期
        icPackage.setYouxiaoqi(jsonObject.getInteger("cycle").toString());
        //月用量限额(MB)
        icPackage.setMonthXiane(jsonObject.getDouble("flowLimit").toString());
        //月用量限制1限制 2不限制  (渠道 1:限制；0:不限制)
        int isLimit = jsonObject.getIntValue("isLimit");
        icPackage.setIsXianzhi((isLimit==1?CardStatus.YUEXIANZHI_YES.getNum():CardStatus.YUEXIANZHI_NO.getNum())+"");
        //状态：1:启用；0:停用
        int status = jsonObject.getIntValue("status");
        icPackage.setChannalStatus(status);
        if(status==0){
            icPackage.setUseStatus(CardStatus.QIYONG_USE_NO.getNum());
        }
        //渠道
        icPackage.setChannalId(CardStatus.CHANNEL_ZEMI.getNum());
        //运营商

        //成本价
        icPackage.setChengbenjia(jsonObject.getDouble("price").toString());
        return icPackage;
    }
}
